const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
import m from "../models/Good";
import _ from "lodash";
import { Request, Response } from "express";
import { NextFunction } from "express-serve-static-core";

import utils from "../utils";

import * as config from "../config";

router.get("/", function(req: Request, res: Response, next: NextFunction) {
  res.json({
    code: 200,
    data: config,
    msg: "获取成功"
  });
});

router.get("/:id", async (req: Request, res: Response, next: NextFunction) => {
  let ret: any = undefined;
  try {
    ret = await m.findById(req.params.id);
  } catch (e) {
    return next(e);
  }
  res.json({
    code: 200,
    data: ret,
    msg: "success"
  });
});

router.post("/", async (req: Request, res: Response, next: NextFunction) => {
  let ret = undefined;
  try {
    ret = await m.create({ ...req.body });
  } catch (e) {
    return next(e);
  }
  res.json({
    code: 200,
    data: ret,
    msg: "success"
  });
});

router.put("/:id", async (req: Request, res: Response, next: NextFunction) => {
  let ret = undefined;
  try {
    // 这里返回的是上次更新的结果....
    ret = await m.findByIdAndUpdate(req.params.id, { ...req.body });
  } catch (e) {
    return next(e);
  }

  ret = await m.findOne({ _id: req.params.id });

  res.json({
    code: "200",
    data: ret,
    msg: "success"
  });
});

router.delete("/:id", function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  m.findByIdAndRemove(req.params.id, req.body, function(err: any, post: any) {
    if (err) return next(err);
    res.json(post);
  });
});

module.exports = router;
